package com.ruitu.mall_98_seller.ui.order;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hjq.permissions.Permission;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.PhoneUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.dao.bean.Order;
import com.ruitu.mall_98_seller.mvp.model.OrderModel;
import com.ruitu.mall_98_seller.mvp.presenter.OrderPresenter;
import com.ruitu.router_module.Config;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.util.GlideUtil;
import com.ruitu.router_module.util.PermissionUtil;

import java.text.SimpleDateFormat;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;

import static com.ruitu.mall_98_seller.mvp.presenter.OrderPresenter.TIME_PATTERN;

// 第二版订单详情
public class OrderDetail2Activity extends BaseActivity<OrderPresenter.OrderDetailP, OrderModel.OrderDetailM> {
    private TextView tv_status, tv_send_time;// 订单状态,发货时间
    private TextView tv_name_phone, tv_addr;// 联系人及电话,收货地址
    private TextView tv_shop;// 企业名称
    private ImageView iv_shop, iv_pro;// 企业logo,商品图片
    private TextView tv_pro_name, tv_spec, tv_pro_type;// 商品名称,商品型号,销售类型
    private TextView tv_pro_total, tv_discount, tv_postage, tv_order_total;// 商品总价,优惠金额,快递运费,订单总价
    private TextView tv_order_status, tv_order_code, tv_pay_type, tv_crarete_time;// 订单状态,编号,支付方式,创建时间
    private TextView tv_pay_time, tv_send_time2, tv_complete_time;// 付款时间,发货时间,完成时间
    private LinearLayout ll_content;// 内容,用于动态添加预售/预订/拼团订单信息
    private RelativeLayout rl_contact_byuer, rl_phone_byuer;// 联系买家,拨打电话
    private TextView tv_copy_code;// 复制单号

    private Order order;// 传过来的订单对象 (暂时只能使用id属性,因为消息页面跳过来的时候只有id属性)
    private Order d;// 请求得到的订单详情对象

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_order_detail2;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_status = findViewById(R.id.tv_status);
        tv_send_time = findViewById(R.id.tv_send_time);
        tv_name_phone = findViewById(R.id.tv_name_phone);
        tv_addr = findViewById(R.id.tv_addr);
        tv_shop = findViewById(R.id.tv_shop);
        iv_shop = findViewById(R.id.iv_shop);
        iv_pro = findViewById(R.id.iv_pro);
        tv_pro_name = findViewById(R.id.tv_pro_name);
        tv_spec = findViewById(R.id.tv_spec);
        tv_pro_type = findViewById(R.id.tv_pro_type);
        tv_pro_total = findViewById(R.id.tv_pro_total);
        tv_discount = findViewById(R.id.tv_discount);
        tv_postage = findViewById(R.id.tv_postage);
        tv_order_total = findViewById(R.id.tv_order_total);
        tv_order_status = findViewById(R.id.tv_order_status);
        tv_order_code = findViewById(R.id.tv_order_code);
        tv_pay_type = findViewById(R.id.tv_pay_type);
        tv_crarete_time = findViewById(R.id.tv_crarete_time);
        tv_pay_time = findViewById(R.id.tv_pay_time);
        tv_send_time2 = findViewById(R.id.tv_send_time2);
        tv_complete_time = findViewById(R.id.tv_complete_time);
        ll_content = findViewById(R.id.ll_content);
        tv_copy_code = findViewById(R.id.tv_copy_code);
        rl_contact_byuer = findViewById(R.id.rl_contact_byuer);
        rl_phone_byuer = findViewById(R.id.rl_phone_byuer);

        setOnClickListener(tv_copy_code, rl_contact_byuer, rl_phone_byuer);

        order = (Order) getIntent().getSerializableExtra("order");
        p.reqOrderDetail(order.getId());
        showProgress();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_copy_code) {// 复制单号
            if (null == d || TextUtils.isEmpty(d.getOrderId())) {
                ToastUtils.showShortSafe("暂无订单编号");
                return;
            }
            String content = d.getOrderId();
            ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setPrimaryClip(ClipData.newPlainText("订单编号", content));
            ToastUtils.showShortSafe("已复制订单编号");
        }
        if (v == rl_contact_byuer) {// 聊天联系买家
            if (isDetailOk()) {
                Order.OrderIn oIn = d.getOrder();
                //说明融云连接成功
                if (RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) {
                    String title = TextUtils.isEmpty(oIn.getConsigneeName()) ? "买家" : oIn.getConsigneeName();
                    RongIM.getInstance().startPrivateChat(this, oIn.getAccountId(), title);
                } else {
                    ToastUtils.showShortSafe("会话连接中,请稍后重试");
                    Arad.bus.post(new EventModel(19090553));// 提示主页面请求融云token并连接
                }
            }
        }
        if (v == rl_phone_byuer) {// 电话联系买家
            if (isDetailOk()) {
                PermissionUtil.handleSinglePermission(this, Permission.CALL_PHONE, "拨打电话", new PermissionUtil.PermissionListener() {
                    @Override
                    public void onPermissionOk(boolean isOk) {
                        if (isOk) {
                            Order.OrderIn oIn = d.getOrder();
                            try {
                                PhoneUtils.dial(oIn.getCollectGoodsPhone());
                            } catch (Exception e) {
                                ToastUtils.showShortSafe("无权限或设备不支持拨号");
                            }
                        }
                    }

                    @Override
                    public void onOpenPermissionPage(boolean isOpen) {

                    }
                });
            }
        }
    }

    private boolean isDetailOk() {
        if (null == d || null == d.getOrder()) {
            ToastUtils.showShortSafe("加载中,请稍候重试");
            return false;
        }
        return true;
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {
            // 订单详情
            d = (Order) data;
            // 大订单信息
            Order.OrderIn oIn = d.getOrder();
            tv_status.setText(new OrderPresenter.OrderListP().getStatus(d.getOrderStatus(), oIn.getIsPayOver(), oIn.getCollageStatus(), d.getOrderType()));
            tv_send_time.setText("发货时间:" + (null == d.getShippingTime() ? "未发货" : new SimpleDateFormat(TIME_PATTERN).format(d.getShippingTime())));
            tv_name_phone.setText(oIn.getConsigneeName() + "    " + oIn.getCollectGoodsPhone());
            tv_addr.setText(oIn.getOrderProvinceCode() + oIn.getOrderCityCode() + oIn.getOrderCountyCode() + oIn.getCollectGoodsAddress());
            tv_shop.setText(d.getCompanyName());
            tv_pro_name.setText(d.getGoodsName());
            tv_spec.setText((TextUtils.isEmpty(d.getSkuContent()) ? "  " : d.getSkuContent()) + "    x" + d.getQuantity());
            tv_pro_type.setText("[" + new OrderPresenter.OrderListP().getType(d.getOrderType()) + "]");
            tv_pro_total.setText("商品总价                    " + d.getGoodsTotal() + "元");
            tv_discount.setText("优惠金额                    " + oIn.getDiscountTotal() + "元");
            tv_postage.setText("快递运费                    " + d.getFreight() + "元");
            tv_order_total.setText("订单总价                    " + oIn.getOrderTotal() + "元");
            tv_order_status.setText("订单状态:    " + new OrderPresenter.OrderListP().getStatus(d.getOrderStatus(), oIn.getIsPayOver(), oIn.getCollageStatus(), d.getOrderType()));
            tv_order_code.setText("订单编号:    " + d.getOrderId());
            tv_pay_type.setText("支付方式:    " + p.getPayType(d.getPaymentType()));
            tv_crarete_time.setText("创建时间:    " + new SimpleDateFormat(TIME_PATTERN).format(d.getCreateTime()));
            tv_pay_time.setText("付款时间:    " + (null == d.getPayTime() ? "未支付" : new SimpleDateFormat(TIME_PATTERN).format(d.getPayTime())));
            tv_send_time2.setText("发货时间:    " + (null == d.getShippingTime() ? "未发货" : new SimpleDateFormat(TIME_PATTERN).format(d.getShippingTime())));
            tv_complete_time.setText("完成时间:    " + (null == d.getFinishTime() ? "未完成" : new SimpleDateFormat(TIME_PATTERN).format(d.getFinishTime())));

            GlideUtil.loadImg(Config.BASE_URL + d.getCompanyLogo(), iv_shop);
            GlideUtil.loadImg(Config.BASE_URL + d.getGoodsUrl(), iv_pro);

            // 预售信息
            Order.PreSale pre = d.getGoodsPreSale();
            if (null != pre) {
                View v = View.inflate(this, R.layout.layout_pre_sale_order, null);
                ((TextView) v.findViewById(R.id.tv_pre_money)).setText("预付订金:    " + oIn.getAdvanceMoney() + "元");
                ((TextView) v.findViewById(R.id.tv_pre_ratio)).setText("预付比例:    " + pre.getPreSaleRatio() + "%");
                ((TextView) v.findViewById(R.id.tv_tail_money)).setText("需付尾款:    " + oIn.getTailMoney() + "元");
                ((TextView) v.findViewById(R.id.tv_send_time)).setText("发货时间:    " + pre.getPreSaleDelivey() + "天");
                ll_content.addView(v);
            }
            // 预订信息
            Order.Reserve res = d.getGoodsReserve();
            if (null != res) {
                View v = View.inflate(this, R.layout.layout_reserve_order, null);
                ((TextView) v.findViewById(R.id.tv_pre_money)).setText("预付订金:    " + oIn.getAdvanceMoney() + "元");
                ((TextView) v.findViewById(R.id.tv_pre_status)).setText("预付状态:    " + p.getReserveStatus(oIn.getIsPayOver()));
                ((TextView) v.findViewById(R.id.tv_tail_money)).setText("需付尾款:    " + oIn.getTailMoney() + "元");
                ((TextView) v.findViewById(R.id.tv_send_time)).setText("发货时间:    " + (null == res.getDeliveryTime() ? "未发货" : new SimpleDateFormat(TIME_PATTERN).format(res.getDeliveryTime())));
                ((TextView) v.findViewById(R.id.tv_require)).setText("需求描述:    " + res.getIntro());
                ll_content.addView(v);
            }
            // 拼团信息
            Order.Collage col = d.getGoodsCollage();
            if (null != col) {
                View v = View.inflate(this, R.layout.layout_collague_order, null);
                ((TextView) v.findViewById(R.id.tv_col_num)).setText("拼团人数:    " + col.getCollageNum());
                ((TextView) v.findViewById(R.id.tv_now_num)).setText("现有人数:    " + col.getExistingNum());
                ((TextView) v.findViewById(R.id.tv_col_status)).setText("拼团状态:    " + p.getCollageStatus(col.getStatus()));
                ((TextView) v.findViewById(R.id.tv_out_time)).setText("超时时间:    " + (null == col.getEndTime() ? "未超时" : new SimpleDateFormat(TIME_PATTERN).format(col.getEndTime())));
                ll_content.addView(v);
            }
        }
    }
}
